#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
低位龙头股分析器Web界面
使用Flask框架构建简单的Web界面，展示低位龙头股分析结果
"""

import os
import sys
import json
import logging
from flask import Flask, render_template, request, jsonify, send_from_directory
from datetime import datetime, timedelta
from src.analyzers.enhanced_leading_stock_analyzer import EnhancedLeadingStockAnalyzer
from src.web.backtesting_routes import backtesting_bp  # 导入回测系统的Blueprint
from src.utils.news_updater import NewsUpdater  # 导入新闻更新器

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 创建Flask应用
app = Flask(__name__, static_folder='static', template_folder='templates')
app.register_blueprint(backtesting_bp)  # 注册回测系统的Blueprint

# 创建全局NewsUpdater实例
news_updater = NewsUpdater()

# 创建必要的目录
def create_directories():
    """创建必要的目录"""
    os.makedirs('static', exist_ok=True)
    os.makedirs('static/img', exist_ok=True)
    os.makedirs('templates', exist_ok=True)
    os.makedirs('static/data', exist_ok=True)
    os.makedirs('data/results', exist_ok=True)
    os.makedirs('data/results/backtesting', exist_ok=True)  # 创建回测报告目录

@app.route('/')
def index():
    """首页"""
    # 获取最新的5条新闻
    latest_news = news_updater.get_latest_news(5)
    
    return render_template('index.html', latest_news=latest_news)

@app.route('/analyze', methods=['POST'])
def analyze():
    """执行分析"""
    try:
        # 获取表单参数
        criteria = {
            'price_to_historical_ratio': float(request.form.get('price_ratio', 0.6)),
            'min_historical_rise': float(request.form.get('min_rise', 100)),
            'max_current_pe': float(request.form.get('max_pe', 50)),
            'min_revenue_growth': float(request.form.get('min_growth', 10)),
            'min_industry_rank': int(request.form.get('min_rank', 5)),
            'min_liquidity': float(request.form.get('min_liquidity', 5000000)),
            'max_downtrend_days': int(request.form.get('max_downtrend', 120))
        }
        
        top_n = int(request.form.get('top_n', 10))
        
        # 初始化分析器
        analyzer = EnhancedLeadingStockAnalyzer()
        
        # 加载数据（确保函数名正确）
        try:
            analyzer.load_stock_data()
        except AttributeError:
            # 如果原方法名不匹配，可能需要调用等效方法
            if hasattr(analyzer, 'get_stock_data'):
                analyzer.get_stock_data()
        
        analyzer.load_historical_price_data()
        analyzer.calculate_industry_rankings()
        
        # 执行分析
        result = analyzer.find_low_position_leaders(criteria=criteria, top_n=top_n)
        
        # 生成图表
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        result_file = f'static/data/result_{timestamp}.json'
        
        with open(result_file, 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
            
        # 复制图表到静态目录
        result_dir = os.path.join('data', 'results', 'low_position_leaders')
        if os.path.exists(os.path.join(result_dir, 'low_position_leaders_scores.png')):
            os.system(f'copy "{os.path.join(result_dir, "low_position_leaders_scores.png")}" "static/img/scores_{timestamp}.png"')
            
        if os.path.exists(os.path.join(result_dir, 'low_position_leaders_radar.png')):
            os.system(f'copy "{os.path.join(result_dir, "low_position_leaders_radar.png")}" "static/img/radar_{timestamp}.png"')
            
        return jsonify({
            'status': 'success',
            'message': f'成功分析{len(result)}只低位龙头股',
            'result_file': result_file,
            'scores_chart': f'static/img/scores_{timestamp}.png',
            'radar_chart': f'static/img/radar_{timestamp}.png',
            'timestamp': timestamp
        })
        
    except Exception as e:
        logger.error(f"分析过程中出错: {e}")
        return jsonify({
            'status': 'error',
            'message': f'分析失败: {str(e)}'
        })

@app.route('/predict', methods=['POST'])
def predict():
    """预测下一批低位龙头股"""
    try:
        count = int(request.form.get('count', 5))
        
        # 初始化分析器
        analyzer = EnhancedLeadingStockAnalyzer()
        
        # 加载数据（确保函数名正确）
        try:
            analyzer.load_stock_data()
        except AttributeError:
            # 如果原方法名不匹配，可能需要调用等效方法
            if hasattr(analyzer, 'get_stock_data'):
                analyzer.get_stock_data()
                
        analyzer.load_historical_price_data()
        analyzer.calculate_industry_rankings()
        
        # 执行预测
        result = analyzer.predict_next_low_position_leaders(count=count)
        
        # 生成时间戳
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        result_file = f'static/data/prediction_{timestamp}.json'
        
        with open(result_file, 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
            
        # 复制图表到静态目录
        result_dir = os.path.join('data', 'results', 'low_position_leaders')
        if os.path.exists(os.path.join(result_dir, 'predicted_low_leaders.png')):
            os.system(f'copy "{os.path.join(result_dir, "predicted_low_leaders.png")}" "static/img/prediction_{timestamp}.png"')
            
        if os.path.exists(os.path.join(result_dir, 'predicted_low_leaders_industry.png')):
            os.system(f'copy "{os.path.join(result_dir, "predicted_low_leaders_industry.png")}" "static/img/industry_{timestamp}.png"')
            
        return jsonify({
            'status': 'success',
            'message': f'成功预测{len(result)}只可能崛起的低位龙头股',
            'result_file': result_file,
            'prediction_chart': f'static/img/prediction_{timestamp}.png',
            'industry_chart': f'static/img/industry_{timestamp}.png',
            'timestamp': timestamp
        })
        
    except Exception as e:
        logger.error(f"预测过程中出错: {e}")
        return jsonify({
            'status': 'error',
            'message': f'预测失败: {str(e)}'
        })

@app.route('/results')
def results():
    """显示历史分析结果"""
    data_dir = 'static/data'
    results = []
    
    if os.path.exists(data_dir):
        for filename in os.listdir(data_dir):
            if filename.startswith('result_') and filename.endswith('.json'):
                timestamp = filename.replace('result_', '').replace('.json', '')
                results.append({
                    'type': '分析',
                    'file': os.path.join(data_dir, filename),
                    'timestamp': timestamp,
                    'datetime': datetime.strptime(timestamp.split('_')[0], '%Y%m%d').strftime('%Y-%m-%d')
                })
            elif filename.startswith('prediction_') and filename.endswith('.json'):
                timestamp = filename.replace('prediction_', '').replace('.json', '')
                results.append({
                    'type': '预测',
                    'file': os.path.join(data_dir, filename),
                    'timestamp': timestamp,
                    'datetime': datetime.strptime(timestamp.split('_')[0], '%Y%m%d').strftime('%Y-%m-%d')
                })
    
    # 按时间戳排序，最新的在前
    results.sort(key=lambda x: x['timestamp'], reverse=True)
    
    return render_template('results.html', results=results)

@app.route('/view/<result_type>/<timestamp>')
def view_result(result_type, timestamp):
    """查看特定分析结果"""
    if result_type == 'analysis':
        filename = f'static/data/result_{timestamp}.json'
        scores_chart = f'static/img/scores_{timestamp}.png'
        radar_chart = f'static/img/radar_{timestamp}.png'
        
        if os.path.exists(filename):
            with open(filename, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            return render_template('view_analysis.html', 
                                  data=data, 
                                  scores_chart=scores_chart if os.path.exists(scores_chart) else None,
                                  radar_chart=radar_chart if os.path.exists(radar_chart) else None,
                                  timestamp=timestamp)
    elif result_type == 'prediction':
        filename = f'static/data/prediction_{timestamp}.json'
        prediction_chart = f'static/img/prediction_{timestamp}.png'
        industry_chart = f'static/img/industry_{timestamp}.png'
        
        if os.path.exists(filename):
            with open(filename, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            return render_template('view_prediction.html', 
                                  data=data, 
                                  prediction_chart=prediction_chart if os.path.exists(prediction_chart) else None,
                                  industry_chart=industry_chart if os.path.exists(industry_chart) else None,
                                  timestamp=timestamp)
    
    return "结果不存在", 404

@app.route('/news')
def news():
    """市场新闻页面"""
    # 获取查询参数
    days = request.args.get('days', '7')  # 默认显示最近7天的新闻
    keywords = request.args.get('keywords', '')  # 关键词搜索
    
    try:
        days = int(days)
    except ValueError:
        days = 7
    
    # 根据参数获取新闻
    if keywords:
        # 关键词搜索
        news_items = news_updater.get_news_by_keywords(keywords.split(','))
    else:
        # 获取最近n天的新闻
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days)
        news_items = news_updater.get_news_by_time_range(start_date, end_date)
    
    # 按时间倒序排序
    news_items = sorted(news_items, key=lambda x: x.get('publish_time', ''), reverse=True)
    
    return render_template(
        'news.html',
        news_items=news_items,
        days=days,
        keywords=keywords
    )

@app.route('/update_news', methods=['POST'])
def update_news():
    """更新市场新闻"""
    try:
        # 更新新闻
        updated_count = news_updater.update_news()
        
        # 返回结果
        return jsonify({
            'success': True,
            'message': f'成功更新{updated_count}条新闻',
            'count': updated_count
        })
    except Exception as e:
        logger.error(f"更新新闻失败: {e}")
        return jsonify({
            'success': False,
            'message': f'更新新闻失败: {str(e)}'
        }), 500

def create_templates():
    """创建HTML模板"""
    # 创建首页模板
    index_html = """
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>低位龙头股分析系统</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
        <style>
            .header {
                background-color: #343a40;
                color: white;
                padding: 2rem 0;
                margin-bottom: 2rem;
            }
            .card {
                margin-bottom: 1.5rem;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }
            .card-header {
                background-color: #f8f9fa;
                font-weight: bold;
            }
            .result-container {
                display: none;
                margin-top: 2rem;
            }
            .chart-container {
                margin-top: 1.5rem;
                text-align: center;
            }
            .chart-container img {
                max-width: 100%;
                height: auto;
                margin-bottom: 1rem;
            }
            .loading {
                text-align: center;
                display: none;
                margin: 1rem 0;
            }
        </style>
    </head>
    <body>
        <div class="header">
            <div class="container">
                <h1>低位龙头股分析系统</h1>
                <p>识别和预测具有潜力的低位龙头股</p>
            </div>
        </div>
        
        <div class="container">
            <div class="row mb-4">
                <div class="col-12">
                    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                        <div class="container-fluid">
                            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                                <span class="navbar-toggler-icon"></span>
                            </button>
                            <div class="collapse navbar-collapse" id="navbarNav">
                                <ul class="navbar-nav">
                                    <li class="nav-item">
                                        <a class="nav-link active" href="/">首页</a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" href="/results">历史结果</a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" href="/backtesting">回测系统</a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" href="/news">市场新闻</a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </nav>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">低位龙头股分析</div>
                        <div class="card-body">
                            <form id="analyzeForm">
                                <div class="mb-3">
                                    <label for="price_ratio" class="form-label">价格比例（当前价格/历史高点）</label>
                                    <input type="number" step="0.01" class="form-control" id="price_ratio" name="price_ratio" value="0.6">
                                    <div class="form-text">建议值: 0.6 (不超过历史高点的60%)</div>
                                </div>
                                <div class="mb-3">
                                    <label for="min_rise" class="form-label">最小历史涨幅（%）</label>
                                    <input type="number" class="form-control" id="min_rise" name="min_rise" value="100">
                                    <div class="form-text">建议值: 100 (历史上至少有100%的涨幅)</div>
                                </div>
                                <div class="mb-3">
                                    <label for="max_pe" class="form-label">最大当前PE</label>
                                    <input type="number" class="form-control" id="max_pe" name="max_pe" value="50">
                                    <div class="form-text">建议值: 50 (当前PE不超过50)</div>
                                </div>
                                <div class="mb-3">
                                    <label for="min_growth" class="form-label">最小收入增长率（%）</label>
                                    <input type="number" class="form-control" id="min_growth" name="min_growth" value="10">
                                    <div class="form-text">建议值: 10 (收入增长至少10%)</div>
                                </div>
                                <div class="mb-3">
                                    <label for="min_rank" class="form-label">最小行业排名</label>
                                    <input type="number" class="form-control" id="min_rank" name="min_rank" value="5">
                                    <div class="form-text">建议值: 5 (行业排名前5)</div>
                                </div>
                                <div class="mb-3">
                                    <label for="min_liquidity" class="form-label">最小日均成交额</label>
                                    <input type="number" class="form-control" id="min_liquidity" name="min_liquidity" value="5000000">
                                    <div class="form-text">建议值: 5000000 (日均成交额至少500万)</div>
                                </div>
                                <div class="mb-3">
                                    <label for="max_downtrend" class="form-label">最大下跌趋势天数</label>
                                    <input type="number" class="form-control" id="max_downtrend" name="max_downtrend" value="120">
                                    <div class="form-text">建议值: 120 (下跌趋势不超过120天)</div>
                                </div>
                                <div class="mb-3">
                                    <label for="top_n" class="form-label">返回结果数量</label>
                                    <input type="number" class="form-control" id="top_n" name="top_n" value="10">
                                </div>
                                <button type="submit" class="btn btn-primary">开始分析</button>
                            </form>
                            <div class="loading" id="analyzeLoading">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p>正在分析，请稍候...</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">预测下一批低位龙头股</div>
                        <div class="card-body">
                            <form id="predictForm">
                                <div class="mb-3">
                                    <label for="count" class="form-label">预测数量</label>
                                    <input type="number" class="form-control" id="count" name="count" value="5">
                                </div>
                                <button type="submit" class="btn btn-success">开始预测</button>
                            </form>
                            <div class="loading" id="predictLoading">
                                <div class="spinner-border text-success" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p>正在预测，请稍候...</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">查看历史结果</div>
                        <div class="card-body">
                            <a href="/results" class="btn btn-info">查看历史分析结果</a>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="result-container" id="analyzeResult">
                <h3>分析结果</h3>
                <div id="analyzeMessage" class="alert alert-success"></div>
                <div class="chart-container">
                    <h4>低位龙头股评分排行</h4>
                    <img id="scoresChart" src="" alt="评分排行">
                </div>
                <div class="chart-container">
                    <h4>多维度评分对比</h4>
                    <img id="radarChart" src="" alt="雷达图">
                </div>
                <div class="mt-3">
                    <button class="btn btn-primary" onclick="window.location.reload()">返回</button>
                </div>
            </div>
            
            <div class="result-container" id="predictResult">
                <h3>预测结果</h3>
                <div id="predictMessage" class="alert alert-success"></div>
                <div class="chart-container">
                    <h4>预测的下一批低位龙头股</h4>
                    <img id="predictionChart" src="" alt="预测结果">
                </div>
                <div class="chart-container">
                    <h4>预测低位龙头股行业分布</h4>
                    <img id="industryChart" src="" alt="行业分布">
                </div>
                <div class="mt-3">
                    <button class="btn btn-primary" onclick="window.location.reload()">返回</button>
                </div>
            </div>
        </div>
        
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function() {
                // 分析表单提交
                $('#analyzeForm').on('submit', function(e) {
                    e.preventDefault();
                    
                    // 显示加载中
                    $('#analyzeLoading').show();
                    
                    // 发送请求
                    $.ajax({
                        url: '/analyze',
                        type: 'POST',
                        data: $(this).serialize(),
                        success: function(response) {
                            $('#analyzeLoading').hide();
                            
                            if (response.status === 'success') {
                                $('#analyzeMessage').text(response.message);
                                $('#scoresChart').attr('src', response.scores_chart);
                                $('#radarChart').attr('src', response.radar_chart);
                                $('#analyzeResult').show();
                                $('#analyzeForm').closest('.card').hide();
                                $('#predictForm').closest('.card').hide();
                            } else {
                                alert('分析失败: ' + response.message);
                            }
                        },
                        error: function() {
                            $('#analyzeLoading').hide();
                            alert('服务器错误，请稍后再试');
                        }
                    });
                });
                
                // 预测表单提交
                $('#predictForm').on('submit', function(e) {
                    e.preventDefault();
                    
                    // 显示加载中
                    $('#predictLoading').show();
                    
                    // 发送请求
                    $.ajax({
                        url: '/predict',
                        type: 'POST',
                        data: $(this).serialize(),
                        success: function(response) {
                            $('#predictLoading').hide();
                            
                            if (response.status === 'success') {
                                $('#predictMessage').text(response.message);
                                $('#predictionChart').attr('src', response.prediction_chart);
                                $('#industryChart').attr('src', response.industry_chart);
                                $('#predictResult').show();
                                $('#analyzeForm').closest('.card').hide();
                                $('#predictForm').closest('.card').hide();
                            } else {
                                alert('预测失败: ' + response.message);
                            }
                        },
                        error: function() {
                            $('#predictLoading').hide();
                            alert('服务器错误，请稍后再试');
                        }
                    });
                });
            });
        </script>
    </body>
    </html>
    """
    
    # 创建结果页模板
    results_html = """
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>历史分析结果 - 低位龙头股分析系统</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
        <style>
            .header {
                background-color: #343a40;
                color: white;
                padding: 2rem 0;
                margin-bottom: 2rem;
            }
            .card {
                margin-bottom: 1.5rem;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }
            .card-header {
                background-color: #f8f9fa;
                font-weight: bold;
            }
        </style>
    </head>
    <body>
        <div class="header">
            <div class="container">
                <h1>历史分析结果</h1>
                <p>查看过往的低位龙头股分析结果</p>
            </div>
        </div>
        
        <div class="container">
            <div class="row mb-4">
                <div class="col-12">
                    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                        <div class="container-fluid">
                            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                                <span class="navbar-toggler-icon"></span>
                            </button>
                            <div class="collapse navbar-collapse" id="navbarNav">
                                <ul class="navbar-nav">
                                    <li class="nav-item">
                                        <a class="nav-link" href="/">首页</a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link active" href="/results">历史结果</a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" href="/backtesting">回测系统</a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" href="/news">市场新闻</a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </nav>
                </div>
            </div>
            
            <div class="card">
                <div class="card-header">历史结果列表</div>
                <div class="card-body">
                    {% if results %}
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>日期</th>
                                        <th>类型</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for result in results %}
                                    <tr>
                                        <td>{{ result.datetime }}</td>
                                        <td>{{ result.type }}</td>
                                        <td>
                                            {% if result.type == '分析' %}
                                                <a href="/view/analysis/{{ result.timestamp }}" class="btn btn-sm btn-info">查看</a>
                                            {% else %}
                                                <a href="/view/prediction/{{ result.timestamp }}" class="btn btn-sm btn-success">查看</a>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <div class="alert alert-info">
                            暂无历史结果记录
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
        
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>
    """
    
    # 创建查看分析结果页模板
    view_analysis_html = """
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>查看分析结果 - 低位龙头股分析系统</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
        <style>
            .header {
                background-color: #343a40;
                color: white;
                padding: 2rem 0;
                margin-bottom: 2rem;
            }
            .card {
                margin-bottom: 1.5rem;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }
            .card-header {
                background-color: #f8f9fa;
                font-weight: bold;
            }
            .chart-container {
                margin-top: 1.5rem;
                text-align: center;
            }
            .chart-container img {
                max-width: 100%;
                height: auto;
                margin-bottom: 1rem;
            }
        </style>
    </head>
    <body>
        <div class="header">
            <div class="container">
                <h1>查看分析结果</h1>
                <p>低位龙头股分析详情</p>
            </div>
        </div>
        
        <div class="container">
            <div class="mb-3">
                <a href="/results" class="btn btn-primary">返回结果列表</a>
                <a href="/" class="btn btn-secondary">返回首页</a>
            </div>
            
            <div class="card">
                <div class="card-header">低位龙头股候选列表</div>
                <div class="card-body">
                    {% if data %}
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>排名</th>
                                        <th>股票名称</th>
                                        <th>行业</th>
                                        <th>当前价格</th>
                                        <th>市盈率</th>
                                        <th>历史价格比</th>
                                        <th>历史涨幅</th>
                                        <th>行业排名</th>
                                        <th>总分</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for stock in data %}
                                    <tr>
                                        <td>{{ loop.index }}</td>
                                        <td>{{ stock.name }}({{ stock.code }})</td>
                                        <td>{{ stock.industry }}</td>
                                        <td>{{ "%.2f"|format(stock.price) }}</td>
                                        <td>{{ "%.2f"|format(stock.pe_ttm) }}</td>
                                        <td>{{ "%.2f"|format(stock.price_to_historical_ratio) }}</td>
                                        <td>{{ "%.2f"|format(stock.historical_rise) }}%</td>
                                        <td>{{ stock.industry_rank }}</td>
                                        <td>{{ "%.2f"|format(stock.total_score) }}</td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <div class="alert alert-info">
                            无分析结果数据
                        </div>
                    {% endif %}
                </div>
            </div>
            
            {% if scores_chart %}
            <div class="chart-container">
                <h4>低位龙头股评分排行</h4>
                <img src="/{{ scores_chart }}" alt="评分排行">
            </div>
            {% endif %}
            
            {% if radar_chart %}
            <div class="chart-container">
                <h4>多维度评分对比</h4>
                <img src="/{{ radar_chart }}" alt="雷达图">
            </div>
            {% endif %}
        </div>
        
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>
    """
    
    # 创建查看预测结果页模板
    view_prediction_html = """
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>查看预测结果 - 低位龙头股分析系统</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
        <style>
            .header {
                background-color: #343a40;
                color: white;
                padding: 2rem 0;
                margin-bottom: 2rem;
            }
            .card {
                margin-bottom: 1.5rem;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }
            .card-header {
                background-color: #f8f9fa;
                font-weight: bold;
            }
            .chart-container {
                margin-top: 1.5rem;
                text-align: center;
            }
            .chart-container img {
                max-width: 100%;
                height: auto;
                margin-bottom: 1rem;
            }
        </style>
    </head>
    <body>
        <div class="header">
            <div class="container">
                <h1>查看预测结果</h1>
                <p>预测的下一批低位龙头股</p>
            </div>
        </div>
        
        <div class="container">
            <div class="mb-3">
                <a href="/results" class="btn btn-primary">返回结果列表</a>
                <a href="/" class="btn btn-secondary">返回首页</a>
            </div>
            
            <div class="card">
                <div class="card-header">预测的低位龙头股列表</div>
                <div class="card-body">
                    {% if data %}
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>排名</th>
                                        <th>股票名称</th>
                                        <th>行业</th>
                                        <th>基础评分</th>
                                        <th>行业热度</th>
                                        <th>热度加成</th>
                                        <th>调整后评分</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for stock in data %}
                                    <tr>
                                        <td>{{ loop.index }}</td>
                                        <td>{{ stock.name }}({{ stock.code }})</td>
                                        <td>{{ stock.industry }}</td>
                                        <td>{{ "%.2f"|format(stock.total_score) }}</td>
                                        <td>{{ "%.2f"|format(stock.industry_heat) }}</td>
                                        <td>{{ "%.2f"|format(stock.heat_bonus) }}</td>
                                        <td>{{ "%.2f"|format(stock.adjusted_score) }}</td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <div class="alert alert-info">
                            无预测结果数据
                        </div>
                    {% endif %}
                </div>
            </div>
            
            {% if prediction_chart %}
            <div class="chart-container">
                <h4>预测的下一批低位龙头股</h4>
                <img src="/{{ prediction_chart }}" alt="预测结果">
            </div>
            {% endif %}
            
            {% if industry_chart %}
            <div class="chart-container">
                <h4>预测低位龙头股行业分布</h4>
                <img src="/{{ industry_chart }}" alt="行业分布">
            </div>
            {% endif %}
        </div>
        
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>
    """
    
    # 创建模板目录
    os.makedirs('templates', exist_ok=True)
    
    # 写入模板文件
    with open('templates/index.html', 'w', encoding='utf-8') as f:
        f.write(index_html)
        
    with open('templates/results.html', 'w', encoding='utf-8') as f:
        f.write(results_html)
        
    with open('templates/view_analysis.html', 'w', encoding='utf-8') as f:
        f.write(view_analysis_html)
        
    with open('templates/view_prediction.html', 'w', encoding='utf-8') as f:
        f.write(view_prediction_html)

def main():
    """主函数"""
    # 创建必要的目录和模板
    create_directories()
    create_templates()
    
    # 启动Flask应用
    app.run(host='0.0.0.0', port=5000, debug=True)

if __name__ == '__main__':
    main() 